using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;

using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ACM.cmsarea08.Controls
{
    [DefaultProperty("Src")]
    [ToolboxData("<{0}:dataimage runat=server></{0}:dataimage>")]
    public class dataimage : Control, IAttributeAccessor
    {
        string _src;
        public dataimage()
        {
            _src = string.Empty;
        }

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Src
        {
            get
            {
                if (ViewState["SRC"] == null)
                    return string.Empty;
                else
                    return ViewState["SRC"].ToString();
                return (this.getImageSrc("src"));
            }

            set
            {
                ViewState["SRC"] = value;
               //setImageSrc("src", value);
            }
        }

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Class
        {
            get
            {
                String s = (String)ViewState["Class"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["Class"] = value;
            }
        }
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Style
        {
            get
            {
                String s = (String)ViewState["Style"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["Style"] = value;
            }
        }
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Alt
        {
            get
            {
                String s = (String)ViewState["Alt"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["Alt"] = value;
            }
        }

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string DefaultImage
        {
            get
            {
                String s = (String)ViewState["DefaultImage"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["DefaultImage"] = value;
            }
        }

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public int Width
        {
            get
            {
                if (ViewState["Width"] == null)
                    return 0;
                int s = 0;
                Int32.TryParse(ViewState["Width"].ToString(), out s);
                return s;
            }

            set
            {
                ViewState["Width"] = value;
            }
        }
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public int Height
        {
            get
            {
                if (ViewState["Height"] == null)
                    return 0;
                int s = 0;
                Int32.TryParse(ViewState["Height"].ToString(), out s);
                return s;

            }

            set
            {
                ViewState["Height"] = value;
            }
        }

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public int ThumbWidth
        {
            get
            {
                if (ViewState["ThumbWidth"] == null)
                    return 0;
                int s = 0;
                Int32.TryParse(ViewState["ThumbWidth"].ToString(), out s);
                return s;
            }

            set
            {
                ViewState["ThumbWidth"] = value;
            }
        }
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public int ThumbHeight
        {
            get
            {
                if (ViewState["ThumbHeight"] == null)
                    return 0;
                int s = 0;
                Int32.TryParse(ViewState["ThumbHeight"].ToString(), out s);
                return s;

            }

            set
            {
                ViewState["ThumbHeight"] = value;
            }
        }


        
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string UniqueKey
        {
            get
            {
                String s = (String)ViewState["UniqueKey"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["UniqueKey"] = value;
            }
        }

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(false)]
        public bool LinkThumb
        {
            get
            {
            	object s = ViewState["LinkThumb"];
            	if(s==null) return false;
            	else return (bool)s;
            }

            set
            {
                ViewState["LinkThumb"] = value;
            }
        }
        
        
        private string Guido
        {
            get
            {
                if (UniqueKey != string.Empty)
                    return UniqueKey;
                object o = ViewState["guido"];
                if (o == null)
                {
                    o = System.Guid.NewGuid().ToString();
                    ViewState["guido"] = o;
                }
                return o.ToString();
            }
        }

		private System.Web.UI.AttributeCollection attrColl;
        private StateBag attrState;
        public System.Web.UI.AttributeCollection Attributes
        {
            get
            {
                if (this.attrColl == null)
                {
                    if (this.attrState == null)
                    {
                        this.attrState = new StateBag(true);

                    }
                    this.attrColl = new System.Web.UI.AttributeCollection(this.attrState);
                }
                return this.attrColl;
            }
        }
        string IAttributeAccessor.GetAttribute(string name)
        {
            if (this.attrState == null)
                return null;
            else
                return (string)this.attrState[name];
        }
        void IAttributeAccessor.SetAttribute(string name, string value)
        {
            this.Attributes[name] = value;
        }
        
        
        
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
        }
        //const string img = "<img src=\"{0}\" alt=\"{1}\" {2} />";

        protected override void Render(HtmlTextWriter writer)
        {
        	string linkthumb ="<a href=\"{0}\" title=\"{1}\" {2} {3} ";
            string img = "<img src=\"{0}\" alt=\"{1}\" {2} {3}  ";
            
            string alto = "";
            if (this.Alt != string.Empty)
                alto = ACM.cmsarea08.Function.TextClass.textclass.CleanHTML(HttpUtility.HtmlDecode(Alt)).Trim();
            if (Src != string.Empty && Src.Length > 0)
            {
                string url = string.Empty;
                string thumburl = string.Empty;
                
                if(Src.ToLower().StartsWith("http:") )
                    url = Src;
                
                if (Src.Length < 260)
                {
                    if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(Src)))
                        url = Src;
                }
                //se contiene un ~
                if (Src.IndexOf('#') != -1)
                {
                    url = this.getVirtualImageUrl(Src,out thumburl);
                }
                if (url.Trim() == "#") url = string.Empty;
                if(url == string.Empty && (!(string.IsNullOrEmpty(this.DefaultImage))))
                    url = this.DefaultImage;
                
                if(url!=string.Empty) {
                	if(LinkThumb) { 
                		writer.Write( string.Format(linkthumb,
                		                            url,
                		                            (alto != string.Empty ? alto : url),
                		                            (Class!=string.Empty?" class=\"" + Class + "\"":"") + (Style!=string.Empty?" style=\"" + this.Style + "\"":"") ,
                		                            "id=\""+this.ClientID+"\"" ) );
		            	Attributes.Render(writer);
		            	writer.Write(">");
		            	writer.Write(string.Format(img,
		            	                           (thumburl!=string.Empty?thumburl:url),
		            	                           (alto != string.Empty ? alto : url),
		            	                           "",
		            	                           ""));
                	} else 
		            	writer.Write(string.Format(img,
		            	                           url,
		            	                           (alto != string.Empty ? alto : url),
		            	                           (Class!=string.Empty?" class=\"" + Class + "\"":"") + (Style!=string.Empty?" style=\"" + this.Style + "\"":"") ,
                		                            "id=\""+this.ClientID+"\"" ));
                		
                } else {
                    writer.Write (string.Format(img, "#", "not found " + (alto != string.Empty ? alto : ""),
                    (Class != string.Empty ? " class=\"" + Class + "\"" : "") +(Style != string.Empty ? " style=\"" + this.Style + "\"" : ""), 
                    "id=\"" + this.ClientID + "\" DefaultImage=\"" +this.DefaultImage +"\" "));
                }
            }
            else
            {
                //not found
                string url = "";
                if (!(string.IsNullOrEmpty(this.DefaultImage)))
                    url = this.DefaultImage;
                else
                    url = "#";
                
                writer.Write(string.Format(img, url, "not found " + (alto != string.Empty ? alto : ""),
                (Class != string.Empty ? " class=\"" + Class + "\"" : "") +(Style != string.Empty ? " style=\"" + this.Style + "\"" : ""),
                ""));
            }
            
            if(LinkThumb==false) {
            	Attributes.Render(writer);
            	writer.Write("/>");
            } else {
            	writer.Write("/>");
            	writer.Write("</a>");
            }
        }

        private string getVirtualImageUrl(object data,out string thumburl)
        {
        	thumburl=string.Empty;
            string valore = "";
            if (data is string)
                valore = data.ToString();
            else if (data is byte[])
                valore = System.Text.Encoding.UTF8.GetString((byte[])data);
            else
            {
                return string.Empty;
            }

            if (valore.IndexOf('#') == -1) return string.Empty;
            //se ci sono dati:
            try
            {
                //string filename = ""; byte[] dati = new byte[0];
                string guido = Guido;// System.Guid.NewGuid().ToString();
                ACM.cmsarea08.Function.CacheFileObjectInfo cInfo = ACM.cmsarea08.Function.CacheManager.cachemanager.getCacheFileObjectInfo(guido);
                if(!cInfo.exists)
                    Function.CacheManager.cachemanager.setCacheFileObject(guido, valore, 180, false);
                if(ThumbWidth!=0 || ThumbHeight!=0) {
	                ACM.cmsarea08.Function.CacheFileObjectInfo thInfo = ACM.cmsarea08.Function.CacheManager.cachemanager.getCacheFileObjectInfo(guido+"thumb");
	                if(!thInfo.exists)
	                    Function.CacheManager.cachemanager.setCacheFileObject(guido+"thumb", valore, 180, false);
            		thumburl ="http://" + Request.ServerVariables["SERVER_NAME"] +
                       "/ImageFileHandler.ashx?gid=" + guido +"thumb&amp;sw=" + ThumbWidth + "&amp;sh=" + ThumbHeight;
                }
                return "http://" + Request.ServerVariables["SERVER_NAME"] +
                       "/ImageFileHandler.ashx?gid=" + guido +"&amp;sw=" + Width + "&amp;sh=" + Height;
            }
            catch //(Exception ex)
            {
                return string.Empty;
            }

        }

        private HttpRequest Request
        {
            get { return HttpContext.Current.Request; }
        }

        
        private void setImageSrc(string key, string src)
        {
            if (this.Page != null)
            {
                if (this.Page.Cache[key] != null)
                    this.Page.Cache.Remove(key);
                this.Page.Cache.Insert(key, src, null, DateTime.Now.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration,
                    CacheItemPriority.High, null);
            }
            else
                this._src = src;
        }
        private string getImageSrc(string key)
        {
            if (this.Page != null)
            {
                if (this.Page.Cache[key] == null)
                    return string.Empty;
                return (String)this.Page.Cache[key];
            }
            else
                return _src;
        }
    }
}
